<template>
  <div class="global-header">
    <el-container>
      <div class="header-content">
        <!-- 左侧Logo和标题 -->
        <div class="header-left">
          <div class="logo-section">
            <img src="../assets/electron.svg" alt="Logo" class="logo" />
            <span class="site-title">Mixed Project</span>
          </div>
        </div>

        <!-- 中间菜单 -->
        <div class="header-center">
          <el-menu
            :default-active="activeIndex"
            mode="horizontal"
            :ellipsis="false"
            @select="handleSelect"
            class="header-menu"
          >
            <el-menu-item
              v-for="item in menuItems"
              :key="item.index"
              :index="item.index"
              :route="item.route"
            >
              <el-icon v-if="item.icon">
                <component :is="item.icon" />
              </el-icon>
              <span>{{ item.title }}</span>
            </el-menu-item>
          </el-menu>
        </div>

        <!-- 右侧用户区域 -->
        <div class="header-right">
          <!-- 未登录状态 -->
          <div v-if="!isLoggedIn" class="auth-buttons">
            <el-button @click="handleRegister">
              <el-icon><UserFilled /></el-icon>
              注册
            </el-button>
            <el-button type="primary" @click="handleLogin">
              <el-icon><User /></el-icon>
              登录
            </el-button>
          </div>

          <!-- 已登录状态 -->
          <div v-else class="user-info">
            <el-dropdown trigger="click" @command="handleUserCommand">
              <div class="user-avatar-section">
                <el-avatar
                  v-if="loginUserStore.loginUser.userAvatar"
                  :src="loginUserStore.loginUser.userAvatar"
                  :size="32"
                />
                <el-avatar v-else :size="32" :icon="UserFilled" />
                <span class="user-name">{{ loginUserStore.loginUser.userName }}</span>
                <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
              </div>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人信息
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="loginUserStore.loginUser.userRole === 'admin'"
                    command="manage"
                  >
                    <el-icon><Setting /></el-icon>
                    系统管理
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, House, InfoFilled, Setting, UserFilled, SwitchButton, ArrowDown, Grid } from '@element-plus/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { logout } from '@/api/userController'

const router = useRouter()
const route = useRoute()
const loginUserStore = useLoginUserStore()

// 菜单配置
const menuItems = computed(() => {
  const items = [
    {
      index: '/',
      title: '首页',
      icon: House,
      route: '/'
    }
  ]
  
  // 只有管理员可以看到管理菜单
  if (loginUserStore.loginUser.userRole === 'admin') {
    items.push(
      {
        index: '/admin/app',
        title: '应用管理',
        icon: Grid,
        route: '/admin/app'
      },
      {
        index: '/admin/userManage',
        title: '用户管理',
        icon: InfoFilled,
        route: '/admin/userManage'
      }
    )
  }
  
  return items
})

// 当前激活的菜单项
const activeIndex = computed(() => {
  return route.path
})

// 是否已登录
const isLoggedIn = computed(() => {
  return loginUserStore.loginUser.userName && loginUserStore.loginUser.userName !== '未登录'
})

// 菜单选择处理
const handleSelect = (key: string) => {
  const menuItem = menuItems.value.find(item => item.index === key)
  if (menuItem && menuItem.route) {
    router.push(menuItem.route)
  }
}

// 登录处理
const handleLogin = () => {
  router.push('/user/login')
}

// 注册处理
const handleRegister = () => {
  router.push('/user/register')
}



// 登出处理
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const result = await logout()
    if (!result.data) {
      ElMessage.error('退出登录失败')
      return
    }
    // 清除登录状态
    loginUserStore.setLoginUser({ userName: '未登录' })

    ElMessage.success('已退出登录')

    // 跳转到首页
    router.push('/')
  } catch (error) {
    // 用户取消登出
  }
}

// 用户下拉菜单命令处理
const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      ElMessage.info('个人信息功能待实现')
      break
    case 'manage':
      // 跳转到用户管理页面
      router.push('/admin/userManage')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 组件挂载时获取登录用户信息
onMounted(() => {
  loginUserStore.fetchLoginUser()
})
</script>

<style scoped>
.global-header {
  width: 100%;
  background-color: #fff;
  border-bottom: 1px solid #e8e8e8;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 64px;
  padding: 0;
  margin: 0 auto;
  width: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  padding-left: 24px;
  flex-shrink: 0;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  height: 40px;
  width: 40px;
  object-fit: contain;
}

.site-title {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  white-space: nowrap;
}

.header-center {
  flex: 1;
  display: flex;
  justify-content: center;
  margin: 0 40px;
}

.header-menu {
  border-bottom: none;
  background-color: transparent;
}

.header-menu .el-menu-item {
  border-bottom: 2px solid transparent;
  margin: 0 8px;
  padding: 0 16px;
  height: 64px;
  line-height: 64px;
}

.header-menu .el-menu-item:hover {
  background-color: #f5f5f5;
  border-bottom-color: #409eff;
}

.header-menu .el-menu-item.is-active {
  background-color: transparent;
  border-bottom-color: #409eff;
  color: #409eff;
}

.header-right {
  display: flex;
  align-items: center;
  padding-right: 24px;
  flex-shrink: 0;
}

.auth-buttons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-avatar-section {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-avatar-section:hover {
  background-color: #f5f5f5;
}

.user-name {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dropdown-icon {
  font-size: 12px;
  color: #6b7280;
  transition: transform 0.2s;
}

.user-avatar-section:hover .dropdown-icon {
  transform: rotate(180deg);
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .header-left {
    padding-left: 16px;
  }

  .header-right {
    padding-right: 16px;
  }

  .header-center {
    margin: 0 20px;
  }
}

@media (max-width: 768px) {
  .header-left {
    padding-left: 12px;
  }

  .header-right {
    padding-right: 12px;
  }

  .site-title {
    font-size: 18px;
  }

  .header-center {
    margin: 0 16px;
  }

  .header-menu .el-menu-item {
    padding: 0 12px;
    margin: 0 4px;
  }
}

@media (max-width: 640px) {
  .header-center {
    display: none;
  }

  .site-title {
    font-size: 16px;
  }

  .logo {
    height: 32px;
    width: 32px;
  }
}
</style>
